package cn.com.hash;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author liufl E-mail:Huberier@allpyra.com
 * @version 创建时间：2017年7月17日 下午4:29:07 类说明
 */
public class HashFunction {
	private MessageDigest md5 = null;

	public long hash(String key) {
		if (md5 == null) {
			try {
				md5 = MessageDigest.getInstance("MD5");
			} catch (NoSuchAlgorithmException e) {
				throw new IllegalStateException("no md5 algrithm found");
			}
		}

		md5.reset();
		md5.update(key.getBytes());
		byte[] bKey = md5.digest();
		// 具体的哈希函数实现细节--每个字节 & 0xFF 再移位
		long result = ((long) (bKey[3] & 0xFF) << 24) | ((long) (bKey[2] & 0xFF) << 16 | ((long) (bKey[1] & 0xFF) << 8) | (long) (bKey[0] & 0xFF));
		return result & 0xffffffffL;
	}
	/**
	 * 非一致性非平衡hash
	 * hash%N
	 * @param args
	 */
	public static void main(String[] args) {
		/*
		 * 一对多分库分表
		 * 用户所有的卡券都在一张表里
		 * 指定卡券ID查询时，通过分库基因快速定位到库
		 */
		int uId0 = "zhangsan".hashCode();
		int uId1 = "lisi".hashCode();
		int uId2 = "wangwu".hashCode();
		int dbSize= 3;
		String suffix_cId = (uId0+"").substring((uId0+"").length()-4, (uId0+"").length());
		String suffix_cId1 = (uId1+"").substring((uId1+"").length()-4, (uId1+"").length());
		String suffix_cId2 = (uId2+"").substring((uId2+"").length()-4, (uId2+"").length());
		System.out.println("zhangsan__hash="+uId0+"  uId0应入库：userCoupon"+suffix_cId);
		System.out.println("lisi______hash="+uId1+"  uId1应入库：userCoupon"+suffix_cId1);
		System.out.println("wangwu____hash="+uId2+"  uId2应入库：userCoupon"+suffix_cId2);
		String cId = System.currentTimeMillis()+("0"+(1+dbSize))+suffix_cId;//1数据库
		String cId1 = System.currentTimeMillis()+("0"+(2+dbSize))+suffix_cId1;//2数据库
		String cId2 = System.currentTimeMillis()+("0"+(3+dbSize))+suffix_cId2;//3数据库
		String src_suffix_cId = cId.substring(cId.length()-4, cId.length());
		String src_suffix_cId1 = cId1.substring(cId1.length()-4, cId1.length());
		String src_suffix_cId2 = cId2.substring(cId2.length()-4, cId2.length());
		System.out.println("分布式cId："+(cId)+"______应查找表：userCoupon"+src_suffix_cId);
		System.out.println("分布式cId1："+(cId1)+"______应查找表：userCoupon"+src_suffix_cId1);
		System.out.println("分布式cId2："+(cId2)+"______应查找表：userCoupon"+src_suffix_cId2);
	}
}
